package logic

import (
	"2210a/commod/models/redisinit"
	"context"
	"fmt"
	"math/rand"
	"time"

	"2210a/commod/commodrpc/commodrpc"
	"2210a/commod/commodrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *commodrpc.SendSmsRequest) (*commodrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	get := redisinit.ClientRedis.Get("one" + in.Username)
	if get.Val() != "" {
		return nil, fmt.Errorf("短信频率限流一分钟只能发送一次")
	}
	ten, _ := redisinit.ClientRedis.Get("smsTen" + in.Source + in.Username).Int()
	if ten >= 10 {
		return nil, fmt.Errorf("短信频率限流每小时只能发送十次")
	}
	code := rand.Intn(9000) + 1000

	//sms, err := pkg.SendSms(in.Username, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if *sms.Body.Code != "OK" {
	//	return nil, fmt.Errorf(pkg.Trl(*sms.Body.Message))
	//}
	incr := redisinit.ClientRedis.Incr("smsTen" + in.Source + in.Username)
	if incr.Val() == 1 {
		redisinit.ClientRedis.Expire("smsTen"+in.Source+in.Username, time.Hour*1)
	}
	redisinit.ClientRedis.Set("sendSms"+in.Source+in.Username, code, time.Minute*5)
	redisinit.ClientRedis.Set("one"+in.Source+in.Username, "1", time.Minute*1)
	//redisinit.ClientRedis.Set("ten"+in.Username, "1", time.Hour*1)

	return &commodrpc.SendSmsResponse{}, nil
}
